﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DBModelConnection
{
    public class ModelWorker
    {
        FileStreamTestEntities1 context = new FileStreamTestEntities1();

        public Video_1 getSpecipicVideo(int id)
        {
            Video_1 video = context.Video_1.FirstOrDefault(item => item.Id == id);
            return video;
        }

        public Dictionary<Banner_1, KeyValuePair<Size_Banner, Time_Banner>> GetAllBannerForVideo(int videoId)
        {
            var dicBanners = new Dictionary<Banner_1, KeyValuePair<Size_Banner, Time_Banner>>();
            var configs = from contract in context.Contract_1
                             where contract.VideoId == videoId
                             select contract.BannerConfig_1;

            var bannerConfig = from config in context.BannerConfig_1 
                       join c in configs on config.Id equals c.Id 
                       select new { config.Banner_1, config.Size_Banner, config.Time_Banner };

            foreach (var item in bannerConfig)
            {
                dicBanners.Add(item.Banner_1, new KeyValuePair<Size_Banner, Time_Banner>(item.Size_Banner, item.Time_Banner));
            }

            return dicBanners;
        }

        public bool AddVideoToDB(Video video)
        {
            context.AddToVideo(video);
            return context.SaveChanges() > 0;
        }

        public bool DeleteVideoById(int id)
        {
            Video removeVideo = context.Video.FirstOrDefault(video => video.Id == id);
            context.Video.DeleteObject(removeVideo);
            return context.SaveChanges() > 0;
        }

        public bool UpdateVideoById(int id, string name, byte[] videoStream, byte[] imageStream)
        {
            Video updateVideo = context.Video.FirstOrDefault(video => video.Id == id);
            updateVideo.Name = name;
            updateVideo.Thumbnail = imageStream;
            updateVideo.VideoFile = videoStream;
            return context.SaveChanges() > 0;
        }

        public byte[] GetVideoByteArrayById(int video_id)
        {
            //Video video = context.Video.FirstOrDefault(item => item.Id == video_id);
            //return video.VideoFile;
            return null;
        }

        public List<Video_1> GetAllSmallImageVideos()
        {
            var list = (from contract in context.Contract_1
                       select contract.Video_1).Distinct();

            List<Video_1> myList = new List<Video_1>();
            foreach (var item in list)
            {
                myList.Add(new Video_1()
                { 
                    Id = item.Id,
                    ThunmbnailUrl = item.ThunmbnailUrl,
                    Name = item.Name
                });
            }
            return myList;
        }
    }
}
